import { useState, useEffect, use, useActionState, useFormStatus, useOptimistic, startTransition } from "react";
import "./React19Features.css";

// 模拟异步操作
const fetchData = async (url) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({ data: `从 ${url} 获取的数据`, timestamp: Date.now() });
    }, 1000);
  });
};

// 模拟用户数据 API
const userAPI = {
  async getUser(id) {
    await new Promise(resolve => setTimeout(resolve, 800));
    return {
      id,
      name: `用户 ${id}`,
      email: `user${id}@example.com`,
      avatar: `https://picsum.photos/seed/user${id}/100/100.jpg`
    };
  },
  
  async updateUser(id, data) {
    await new Promise(resolve => setTimeout(resolve, 1000));
    return { success: true, ...data };
  }
};

// use Hook 示例
function UseHookExample() {
  const [resource, setResource] = useState(null);
  const [userId, setUserId] = useState(1);
  
  useEffect(() => {
    const userPromise = userAPI.getUser(userId);
    setResource(userPromise);
  }, [userId]);
  
  const user = resource ? use(resource) : null;
  
  return (
    <div className="example-container">
      <h4>use Hook 示例</h4>
      
      <div className="controls">
        <button onClick={() => setUserId(1)}>加载用户 1</button>
        <button onClick={() => setUserId(2)}>加载用户 2</button>
        <button onClick={() => setUserId(3)}>加载用户 3</button>
      </div>
      
      <div className="user-display">
        {user ? (
          <div className="user-card">
            <img src={user.avatar} alt={user.name} className="user-avatar" />
            <div className="user-info">
              <h3>{user.name}</h3>
              <p>{user.email}</p>
              <p>ID: {user.id}</p>
            </div>
          </div>
        ) : (
          <div className="loading">加载中...</div>
        )}
      </div>
      
      <div className="feature-description">
        <p><strong>use Hook:</strong> React 19 新增的 Hook，用于在组件中读取 Promise、Context 等资源的值。</p>
        <p>优势：简化异步数据获取，自动处理加载状态，支持 Suspense 边界。</p>
      </div>
    </div>
  );
}

// useActionState 示例
function UseActionStateExample() {
  const [state, formAction, isPending] = useActionState(
    async (prevState, formData) => {
      const name = formData.get('name');
      const email = formData.get('email');
      
      if (!name || !email) {
        return { error: '请填写所有字段' };
      }
      
      try {
        await new Promise(resolve => setTimeout(resolve, 1000));
        return { success: true, message: `用户 ${name} 创建成功！` };
      } catch (error) {
        return { error: '创建失败，请重试' };
      }
    },
    null
  );
  
  return (
    <div className="example-container">
      <h4>useActionState 示例</h4>
      
      <form action={formAction} className="user-form">
        <div className="form-group">
          <label htmlFor="name">姓名</label>
          <input type="text" id="name" name="name" disabled={isPending} />
        </div>
        
        <div className="form-group">
          <label htmlFor="email">邮箱</label>
          <input type="email" id="email" name="email" disabled={isPending} />
        </div>
        
        <button type="submit" disabled={isPending}>
          {isPending ? '创建中...' : '创建用户'}
        </button>
        
        {state?.error && (
          <div className="error-message">{state.error}</div>
        )}
        
        {state?.success && (
          <div className="success-message">{state.message}</div>
        )}
      </form>
      
      <div className="feature-description">
        <p><strong>useActionState:</strong> 管理表单操作的状态，包括加载状态、错误和成功消息。</p>
        <p>优势：简化表单状态管理，自动处理提交状态，支持乐观更新。</p>
      </div>
    </div>
  );
}

// useFormStatus 示例
function SubmitButton() {
  const { pending } = useFormStatus();
  
  return (
    <button type="submit" disabled={pending}>
      {pending ? '提交中...' : '提交'}
    </button>
  );
}

function UseFormStatusExample() {
  const [message, setMessage] = useState('');
  
  const handleSubmit = async (formData) => {
    const content = formData.get('content');
    
    await new Promise(resolve => setTimeout(resolve, 1500));
    setMessage(`消息已发送: ${content}`);
  };
  
  return (
    <div className="example-container">
      <h4>useFormStatus 示例</h4>
      
      <form action={handleSubmit} className="message-form">
        <div className="form-group">
          <label htmlFor="content">消息内容</label>
          <textarea 
            id="content" 
            name="content" 
            rows="4" 
            placeholder="输入您的消息..."
          />
        </div>
        
        <SubmitButton />
        
        {message && (
          <div className="success-message">{message}</div>
        )}
      </form>
      
      <div className="feature-description">
        <p><strong>useFormStatus:</strong> 在表单内部组件中访问表单的提交状态。</p>
        <p>优势：让子组件知道表单是否正在提交，无需传递 props。</p>
      </div>
    </div>
  );
}

// useOptimistic 示例
function UseOptimisticExample() {
  const [messages, setMessages] = useState([
    { id: 1, text: '欢迎来到聊天室！', sent: false }
  ]);
  
  const [optimisticMessages, addOptimisticMessage] = useOptimistic(
    messages,
    (state, newMessage) => [
      ...state,
      { ...newMessage, id: Date.now(), sending: true }
    ]
  );
  
  const [formData, setFormData] = useState({ text: '' });
  
  const handleSubmit = async (e) => {
    e.preventDefault();
    
    if (!formData.text.trim()) return;
    
    const newMessage = { text: formData.text, sent: true };
    
    // 添加乐观更新
    addOptimisticMessage(newMessage);
    
    try {
      // 模拟发送消息
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      // 更新实际消息
      setMessages(prev => [...prev, { ...newMessage, id: Date.now() }]);
      setFormData({ text: '' });
    } catch (error) {
      console.error('发送失败:', error);
    }
  };
  
  return (
    <div className="example-container">
      <h4>useOptimistic 示例</h4>
      
      <div className="chat-container">
        <div className="messages">
          {optimisticMessages.map((message, index) => (
            <div 
              key={message.id || index} 
              className={`message ${message.sent ? 'sent' : 'received'} ${message.sending ? 'sending' : ''}`}
            >
              <span className="message-text">{message.text}</span>
              {message.sending && <span className="sending-indicator">发送中...</span>}
            </div>
          ))}
        </div>
        
        <form onSubmit={handleSubmit} className="message-input-form">
          <input
            type="text"
            value={formData.text}
            onChange={(e) => setFormData({ text: e.target.value })}
            placeholder="输入消息..."
            className="message-input"
          />
          <button type="submit">发送</button>
        </form>
      </div>
      
      <div className="feature-description">
        <p><strong>useOptimistic:</strong> 在异步操作完成前乐观地更新 UI。</p>
        <p>优势：提升用户体验，让应用感觉更快，自动处理回滚。</p>
      </div>
    </div>
  );
}

// startTransition 示例
function StartTransitionExample() {
  const [input, setInput] = useState('');
  const [searchResults, setSearchResults] = useState([]);
  const [isPending, startTransition] = useTransition();
  
  const handleChange = (e) => {
    // 立即更新输入框
    setInput(e.target.value);
    
    // 使用 transition 处理搜索结果更新
    startTransition(() => {
      if (e.target.value) {
        // 模拟搜索
        const results = Array.from({ length: 20 }, (_, i) => ({
          id: i + 1,
          title: `搜索结果 ${i + 1} for "${e.target.value}"`,
          description: `这是关于 "${e.target.value}" 的搜索结果描述`
        }));
        setSearchResults(results);
      } else {
        setSearchResults([]);
      }
    });
  };
  
  return (
    <div className="example-container">
      <h4>startTransition 示例</h4>
      
      <div className="search-container">
        <input
          type="text"
          value={input}
          onChange={handleChange}
          placeholder="搜索..."
          className="search-input"
        />
        
        {isPending && (
          <div className="search-indicator">搜索中...</div>
        )}
        
        <div className="search-results">
          {searchResults.map(result => (
            <div key={result.id} className="search-result-item">
              <h4>{result.title}</h4>
              <p>{result.description}</p>
            </div>
          ))}
        </div>
      </div>
      
      <div className="feature-description">
        <p><strong>startTransition:</strong> 将状态更新标记为过渡，允许 React 中断渲染。</p>
        <p>优势：保持 UI 响应性，避免输入卡顿，提供更好的用户体验。</p>
      </div>
    </div>
  );
}

// 服务器组件示例（模拟）
function ServerComponentExample() {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(false);
  
  const loadData = async () => {
    setLoading(true);
    try {
      const result = await fetchData('/api/server-data');
      setData(result);
    } catch (error) {
      console.error('加载失败:', error);
    } finally {
      setLoading(false);
    }
  };
  
  return (
    <div className="example-container">
      <h4>服务器组件示例</h4>
      
      <div className="server-component-demo">
        <button onClick={loadData} disabled={loading}>
          {loading ? '加载中...' : '加载服务器数据'}
        </button>
        
        {data && (
          <div className="server-data">
            <h5>服务器返回的数据:</h5>
            <pre>{JSON.stringify(data, null, 2)}</pre>
          </div>
        )}
      </div>
      
      <div className="feature-description">
        <p><strong>服务器组件:</strong> 在服务器上渲染的组件，可以直接访问服务器资源。</p>
        <p>优势：减少客户端 JavaScript 包大小，更好的 SEO，更快的首屏加载。</p>
      </div>
    </div>
  );
}

// Actions 示例
function ActionsExample() {
  const [todos, setTodos] = useState([
    { id: 1, text: '学习 React 19 新特性', completed: false },
    { id: 2, text: '创建示例项目', completed: true }
  ]);
  
  const addTodo = async (formData) => {
    const text = formData.get('todo');
    if (!text.trim()) return;
    
    await new Promise(resolve => setTimeout(resolve, 500));
    
    setTodos(prev => [...prev, {
      id: Date.now(),
      text,
      completed: false
    }]);
  };
  
  const toggleTodo = async (id) => {
    await new Promise(resolve => setTimeout(resolve, 300));
    
    setTodos(prev => prev.map(todo =>
      todo.id === id ? { ...todo, completed: !todo.completed } : todo
    ));
  };
  
  const deleteTodo = async (id) => {
    await new Promise(resolve => setTimeout(resolve, 300));
    
    setTodos(prev => prev.filter(todo => todo.id !== id));
  };
  
  return (
    <div className="example-container">
      <h4>Actions 示例</h4>
      
      <div className="todos-container">
        <form action={addTodo} className="add-todo-form">
          <input type="text" name="todo" placeholder="添加新任务..." />
          <button type="submit">添加</button>
        </form>
        
        <ul className="todo-list">
          {todos.map(todo => (
            <li key={todo.id} className={`todo-item ${todo.completed ? 'completed' : ''}`}>
              <span 
                className="todo-text"
                onClick={() => toggleTodo(todo.id)}
              >
                {todo.text}
              </span>
              <button 
                className="delete-btn"
                onClick={() => deleteTodo(todo.id)}
              >
                删除
              </button>
            </li>
          ))}
        </ul>
      </div>
      
      <div className="feature-description">
        <p><strong>Actions:</strong> 简化异步操作的处理，自动管理状态和错误。</p>
        <p>优势：减少样板代码，更好的错误处理，支持乐观更新。</p>
      </div>
    </div>
  );
}

// 文档元数据示例
function DocumentMetadataExample() {
  const [title, setTitle] = useState('React 19 新特性');
  const [description, setDescription] = useState('探索 React 19 的最新功能');
  
  useEffect(() => {
    document.title = title;
    
    let metaDescription = document.querySelector('meta[name="description"]');
    if (!metaDescription) {
      metaDescription = document.createElement('meta');
      metaDescription.name = 'description';
      document.head.appendChild(metaDescription);
    }
    metaDescription.content = description;
  }, [title, description]);
  
  return (
    <div className="example-container">
      <h4>文档元数据示例</h4>
      
      <div className="metadata-form">
        <div className="form-group">
          <label htmlFor="title">页面标题</label>
          <input
            type="text"
            id="title"
            value={title}
            onChange={(e) => setTitle(e.target.value)}
          />
        </div>
        
        <div className="form-group">
          <label htmlFor="description">页面描述</label>
          <textarea
            id="description"
            value={description}
            onChange={(e) => setDescription(e.target.value)}
            rows="3"
          />
        </div>
      </div>
      
      <div className="metadata-info">
        <p>查看浏览器标题栏和页面源代码中的元数据变化</p>
      </div>
      
      <div className="feature-description">
        <p><strong>文档元数据:</strong> React 19 提供了更好的文档元数据管理方式。</p>
        <p>优势：SEO 友好，更好的可访问性，简化元数据管理。</p>
      </div>
    </div>
  );
}

// 资源加载示例
function ResourceLoadingExample() {
  const [resource, setResource] = useState(null);
  const [error, setError] = useState(null);
  
  const loadResource = async () => {
    try {
      setError(null);
      const dataPromise = fetchData('/api/resource');
      setResource(dataPromise);
    } catch (err) {
      setError(err.message);
    }
  };
  
  const data = resource ? use(resource) : null;
  
  return (
    <div className="example-container">
      <h4>资源加载示例</h4>
      
      <div className="resource-controls">
        <button onClick={loadResource}>加载资源</button>
      </div>
      
      <div className="resource-display">
        {error && (
          <div className="error-message">加载失败: {error}</div>
        )}
        
        {data ? (
          <div className="resource-data">
            <h5>资源数据:</h5>
            <pre>{JSON.stringify(data, null, 2)}</pre>
          </div>
        ) : (
          <div className="placeholder">点击按钮加载资源</div>
        )}
      </div>
      
      <div className="feature-description">
        <p><strong>资源加载:</strong> React 19 改进了异步资源的处理方式。</p>
        <p>优势：更好的错误边界，自动重试机制，改进的 Suspense 支持。</p>
      </div>
    </div>
  );
}

// 主组件
function React19Features() {
  const [activeTab, setActiveTab] = useState('use');
  
  const tabs = [
    { id: 'use', label: 'use Hook', component: UseHookExample },
    { id: 'actionState', label: 'useActionState', component: UseActionStateExample },
    { id: 'formStatus', label: 'useFormStatus', component: UseFormStatusExample },
    { id: 'optimistic', label: 'useOptimistic', component: UseOptimisticExample },
    { id: 'transition', label: 'startTransition', component: StartTransitionExample },
    { id: 'server', label: '服务器组件', component: ServerComponentExample },
    { id: 'actions', label: 'Actions', component: ActionsExample },
    { id: 'metadata', label: '文档元数据', component: DocumentMetadataExample },
    { id: 'resource', label: '资源加载', component: ResourceLoadingExample }
  ];
  
  const ActiveComponent = tabs.find(tab => tab.id === activeTab)?.component || UseHookExample;
  
  return (
    <div className="react19-features">
      <h2>React 19 新特性</h2>
      
      <div className="intro-section">
        <p>React 19 引入了许多令人兴奋的新特性，包括新的 Hooks、改进的服务器组件支持、更好的性能优化等。</p>
      </div>
      
      <div className="tab-navigation">
        {tabs.map(tab => (
          <button
            key={tab.id}
            className={`tab-btn ${activeTab === tab.id ? 'active' : ''}`}
            onClick={() => setActiveTab(tab.id)}
          >
            {tab.label}
          </button>
        ))}
      </div>
      
      <div className="tab-content">
        <ActiveComponent />
      </div>
    </div>
  );
}

export default React19Features;